package com.argrace.smart.rokid;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.argrace.smart.ArgraceApplication;
import com.argrace.smart.base.ConstantConfigure;
import com.argrace.smart.thread.MySendUdpThread;

import java.io.IOException;
import java.util.TimerTask;

/**
 * Created by argrace_dev_1 on 2018/2/25.
 */

public class RokidMulticastServer extends Service {
    private final static int GRAY_SERVICE_ID = 1001;
    private int port = 1900;
    private String add = "239.255.255.250";
    private int Local_SendPort = 12344;
    Thread thread_recieve;
    String id;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        startRecieverThread();
        startTcpListenerAndSendKeepAlive();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent innerIntent = new Intent(this, GrayInnerService.class);
        startService(innerIntent);
        startForeground(GRAY_SERVICE_ID, new Notification());
        return super.onStartCommand(intent, flags, startId);
    }
    @SuppressLint("WrongConstant")
    private void startRecieverThread() {
        String androidID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        id = androidID + Build.SERIAL;
        ArgraceApplication.Device_ID = id;
        //监听239.255.255.250：1900的多播，收到多播后，发送单播
        RokidMulticastRecieverThread runnable_recieve = new RokidMulticastRecieverThread(add, port, new RokidMulticastRecieverThread.RecieveUdpThreadCallBack() {
            //收到组播后的回调
            @Override
            public void callBack(String msg) {
                String str_ip = msg.substring("UDP_LOCATION:".length(), msg.length()).trim();
                final String[] args = str_ip.split(":");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //收到组播后发送单播并开始等待TCP客户连接
                        sendSSDP(args[0], Integer.parseInt(args[1]));
                    }
                }).start();

            }
        });
        //监听组播开启
        thread_recieve = new Thread(runnable_recieve, "recieve");
        if (thread_recieve.isAlive()) {
            Toast.makeText(this, "监听已启动，请勿重复", 3000).show();
        } else {
            thread_recieve.start();
        }
    }

    private void sendSSDP(String add, int port) {
        SSDPSocket sock = null;
        try {

            sock = new SSDPSocket(add, port, ConstantConfigure.ROKID_PROT);
            sock.send(getSSDPDanBoSrt());
            Log.i("info","收到UDP广播后发送的数据是" + getSSDPDanBoSrt());
            sock.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private final String SL_NOTIFY = "NOTIFY * HTTP/1.1";
    private final String NEWLINE = "\r\n";
    private final String HOST = "Host:" + "239.255.255.250" + ":" + 1900;

    private String getSSDPDanBoSrt() {
        StringBuilder content = new StringBuilder();
        content.append(SL_NOTIFY).append(NEWLINE);
        content.append(HOST).append(NEWLINE);
        content.append("NT: homebase:device").append(NEWLINE);
        content.append("NTS: ssdp:alive").append(NEWLINE);
        content.append("USN: uuid:" + id).append(NEWLINE);
        content.append("LOCATION: tcp://" + getIpAddress() + ":" + ConstantConfigure.ROKID_TCPLISTENER_PORT).append(NEWLINE);
        content.append("CACHE-CONTROL: max-age=1800").append(NEWLINE);
        content.append("DEVICE_TYPE: bridge").append(NEWLINE);
        return content.toString();
    }

    public String getIpAddress() {
        //获取wifi服务
        @SuppressLint("WifiManagerLeak") WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        //判断wifi是否开启
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();

        return (ipAddress & 0xFF) + "." +
                ((ipAddress >> 8) & 0xFF) + "." +
                ((ipAddress >> 16) & 0xFF) + "." +
                (ipAddress >> 24 & 0xFF);
    }
    private void startTcpListenerAndSendKeepAlive()
    {
        TcpListenerThread tcpListenerThread = new TcpListenerThread(getIpAddress(),ConstantConfigure.ROKID_TCPLISTENER_PORT);
        tcpListenerThread.start();
    }
    public static class GrayInnerService extends Service {

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            startForeground(GRAY_SERVICE_ID, new Notification());
            stopForeground(true);
            stopSelf();
            return super.onStartCommand(intent, flags, startId);
        }

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }


    }
}
